/**
  * 618活动的用户信息数据的store
  * @author: Ruan Jiazhen
  * @date: 2024-04-29 10:31:32
* */

import { requestInviteMiaodou } from '@/api/api-miaodou';
import { reqUploadImage } from '@/api/api-others';
import { requestInfo, requestLoginMiaodou, requestLotteryList, requestMiaodouList, requestMyInviteList, requestTaskMiaodou, requestTodayAndWeekMiaodou, requestToken, reqUpdateAvatarAndName } from '@/api/api-user';
import { defaultUserInfo } from '@/static/constant/user-constant';
import { setToken } from '@/utils/local-data';

export const useUser = defineStore('user', () => {
  // #region 用户信息相关

  /** 用户信息 */
  const userInfo = ref<UserInfo>(defaultUserInfo);

  /**
   * 上传并修改用户头像和昵称
   * @param temAvatarPath 临时头像路径
   */
  const uploadAvatarAndName = async (temAvatarPath: string) => {
    let avatarPath = userInfo.value.avatar;

    if (temAvatarPath) {
      let uploadRes: any = null;
      // 上传头像
      uploadRes = (await reqUploadImage(temAvatarPath)).res;
      avatarPath = JSON.parse(uploadRes.data).data.filePath;
    }

    // 修改用户信息
    const updateRes: any = await reqUpdateAvatarAndName(
      avatarPath,
      userInfo.value.nickname,
    );
    console.log('updateRes', updateRes);

    userInfo.value.avatar = avatarPath;
  };

  // #endregion

  /** 喵豆情况 */
  const miaodouStatus = ref<MiaodouStatus>({
    availableMiaodou: 0,
    todayMiaodou: 0,
    weekMiaodou: 0,
    availableReceiveMiaodou: 0,
    inviteMiaodou: 0,
  });

  /** 获取通过邀请累计获得的喵豆数量 */
  const getInviteMiaodou = async () => {
    const res: any = await requestInviteMiaodou();
    const resData: InviteMiaodouResData = res.data;
    miaodouStatus.value.inviteMiaodou = resData.data.change_dou;
  };

  /** 任务情况 */
  const taskStatus = ref<TaskStatus>({
    isFirstLogin: false,
    firstLoginMiaodouInfo: {
      availableFirstLoginMiaodou: 0,
      inviterName: '',
    },
    isBindAlipay: false,
    isRealName: false,
    isFinishActivity: false,
    finishActivityMiaodou: 0,
    isPlayRedPacketRain: false,
    playRedPacketRainMiaodou: 0,
    isPlayWheel: false,
    playWheelMiaodou: 0,
    isPlayTreasureBox: false,
    playTreasureBoxMiaodou: 0,
    isPlayRedPacketWall: false,
    playRedPacketWallMiaodou: 0,
  });

  /** 设置邀请人的信息 */
  const setShareInfo = (shareUserId: string, shareInviteKey: string) => {
    console.log('setShareInfo', shareInviteKey);
    userInfo.value.shareUserId = shareUserId ?? '';
    userInfo.value.shareInviteKey = shareInviteKey ?? '';
  };

  // 获取并设置token
  // const getToken = async (code: string) => {
  //   const res: any = await requestToken(code)
  //   const token = res.data.data.token
  //   setToken(token ?? '')
  // }
  const getToken = (code: string) => new Promise((resolve, reject) => {
    const inviteKey = userInfo?.value?.shareInviteKey?.length >= 5 ? userInfo.value.shareInviteKey : '00000';
    console.log('getToken', code, inviteKey);
    requestToken(code, inviteKey)
      .then((res: any) => {
        const resData: GetTokenResData = res.data;
        const { token } = resData.data;
        setToken(token ?? '');

        // 设置userInfo中的手机号
        userInfo.value.phone = resData.data.phone;
        console.log('userInfo', userInfo.value);
        // 判断token是否为'0'，为'0'则返回错误
        if (token != '0') { resolve(token); } else { reject('token为0'); }
      }).catch((err: any) => {
        reject(err);
      });
  });

  /** 获取并设置用户信息、喵豆情况、任务情况
   * @returns void
   * @description 通过接口获取用户信息、喵豆情况、任务情况，并设置到对应的ref变量中
   */
  const getInfo = async () => {
    const res: any = await requestInfo();
    const resData: UserInfoResData = res.data;
    console.log('resData', resData);
    // 设置用户信息
    userInfo.value = {
      ...userInfo.value,
      nickname: resData.data.activityInfo.emcee_name,
      avatar: resData.data.activityInfo.avator,
      phone: resData.data.activityInfo.phonenumber,
      userId: resData.data.activityInfo.userId,
      inviteKey: resData.data.activityInfo.invite_key,
      isBindOpenId: resData.data.activityInfo.wx_openid_activity != '0',
      canLottery: resData.data.canLottery,
    };

    // 设置喵豆信息
    miaodouStatus.value = {
      ...miaodouStatus.value,
      availableMiaodou: resData.data.activityInfo.miao_dou,
      todayMiaodou: 0,
      weekMiaodou: 0,
      availableReceiveMiaodou: resData.data.activityInfo.available_dou,
    };
    console.log('miaodouStatus', miaodouStatus.value);

    // 设置任务信息
    taskStatus.value = {
      isFirstLogin: resData.data.is_login === '0',
      firstLoginMiaodouInfo: {
        availableFirstLoginMiaodou: resData.data.miao_dou,
        inviterName: resData.data.name,
      },
      isBindAlipay: resData.data.activityInfo.zfb_is_new === '2',
      isRealName: resData.data.activityInfo.sfz_is_new === '2',
      isFinishActivity: resData.data.activityInfo.finish_is_new === '2',
      finishActivityMiaodou: resData.data.activityInfo.finish_dou,
      isPlayRedPacketRain: resData.data.activityInfo.hby_is_new === '1',
      playRedPacketRainMiaodou: resData.data.activityInfo.hby_dou,
      isPlayWheel: resData.data.activityInfo.dzp_is_new === '1',
      playWheelMiaodou: resData.data.activityInfo.dzp_dou,
      isPlayTreasureBox: resData.data.activityInfo.kbx_is_new === '1',
      playTreasureBoxMiaodou: resData.data.activityInfo.kbx_dou,
      isPlayRedPacketWall: resData.data.activityInfo.hbq_is_new === '1',
      playRedPacketWallMiaodou: resData.data.activityInfo.hbq_dou,
    };
    console.log('taskStatus', taskStatus.value);
  };

  /**
   * 获取并设置用户信息中的今日获得喵豆和本周获得喵豆
   * @returns void
   * @description 通过接口获取今日获得喵豆和本周获得喵豆，并且设置到miaodouStatus中的对应数据中
   */
  const getTodayAndWeekMiaodou = async () => {
    const res: any = await requestTodayAndWeekMiaodou();
    const resData: TodayAndWeekMiaodouResData = res.data;
    console.log('getTodayAndWeekMiaodou', resData);
    miaodouStatus.value.todayMiaodou = resData.data.today.change_dou;
    miaodouStatus.value.weekMiaodou = resData.data.weed.change_dou;
  };

  /**
   * 领取登录喵豆
   * @returns boolean
   * @description 通过接口领取第一次登录时赠送的喵豆，并且更新喵豆信息
   */
  const getLoginMiaodou = async () => {
    const res: any = await requestLoginMiaodou();
    console.log('领取登录喵豆', res);
    getInfo();
    return true;
  };

  /**
   * 领取任务喵豆
   * @returns boolean
   * @description 通过接口领取未领取的任务赠送的喵豆，并且更新喵豆信息
   */
  const getTaskMiaodou = async () => {
    const res: any = await requestTaskMiaodou();
    console.log('领取任务喵豆', res);
    getInfo();
    return true;
  };

  /** 喵豆明细列表 */
  const miaodouList = ref<MiaodouDetailList>([]);

  /**
   * 喵豆明细列表
   * @returns void
   * @description 通过接口获取喵豆明细列表，并且更新喵豆明细列表信息
   */
  const getMiaodouList = async () => {
    const res: any = await requestMiaodouList(1, 10);
    console.log('喵豆明细列表', res);
    const resData: MiaodouDetailListResData = res.data;
    miaodouList.value = resData?.data?.list?.map((item) => ({
      content: item.title,
      time: item.send_time,
      desc: item.kind === '1' ? `+${item.change_dou}` : `-${item.change_dou}`,
      descType: item.kind === '1' ? 'miaodou-add' : 'miaodou-reduce',
    })) ?? [];
    console.log('miaodouList', miaodouList.value);
  };

  /** 抽奖记录列表 */
  const lotteryList = ref<LotteryDetailList>([]);

  /**
   * 获取抽奖记录列表
   * @returns void
   * @description 通过接口获取抽奖记录列表，并且更新抽奖记录列表信息
   */
  const getLotteryList = async () => {
    const res: any = await requestLotteryList(1, 10);
    console.log('抽奖记录列表', res);
    const resData: LotteryDetailListResData = res.data;
    // // desc和descType的对应关系
    // const descTypeMap = {
    //   '系统自动'
    lotteryList.value = resData.data.list.map((item) => ({
      content: item.title,
      time: item.sendTime,
      desc: item.sendInfo,
      descType: item.sendType === '1' ? 'lottery-unreceived' : 'lottery-received',
    }));
    console.log('lotteryList', lotteryList.value);
  };

  /** 我的邀请列表 */
  const inviteList = ref<InviteList>([]);

  /**
   * 获取我的邀请列表
   * @returns void
   * @description 通过接口获取我的邀请列表，并且更新我的邀请列表信息
   * @param {number} page 页码
   * @param {number} pageSize 每页数量
    */
  const getInviteList = async (page?: number, pageSize?: number) => {
    const param = {};
    const res: any = await requestMyInviteList();
    console.log('我的邀请列表', res);
    const resData: InviteListResData = res.data;
    inviteList.value = resData?.data?.list.map((item) => ({
      nickname: item.emcee_name,
      avatar: item.avator,
      miaodou: item.money,
      status: item.kind === '1' ? '1' : '2',
    })) ?? [];
    console.log('inviteList', inviteList.value);
  };

  const resetLoginStatus = () => {
    uni.removeStorageSync('token');
    userInfo.value.nickname = '';
    userInfo.value.avatar = '';
    userInfo.value.phone = '';
    userInfo.value.userId = '';
    userInfo.value.inviteKey = '';
    userInfo.value.shareUserId = '';
    userInfo.value.shareInviteKey = '';
    userInfo.value.isBindOpenId = false;
  };
  return {
    userInfo,
    uploadAvatarAndName,
    setShareInfo,
    taskStatus,
    miaodouStatus,
    getInviteMiaodou,
    getToken,
    getInfo,
    getTodayAndWeekMiaodou,
    getLoginMiaodou,
    getTaskMiaodou,
    miaodouList,
    getMiaodouList,
    lotteryList,
    getLotteryList,
    inviteList,
    getInviteList,
    resetLoginStatus,
  };
});
